﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ValidListAttribute.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TongTongMall.MallWeb.Application.Attributes.ModelBinders
{
    public class ValidListAttribute : ValidationAttribute
    {
        /// <summary>
        /// 集合限制的长度
        /// </summary>
        public int LimitLength { get; set; } = 100;

        /// <summary>
        /// 是否允许为空或长度为0
        /// </summary>
        public bool IsNullOrZero { get; set; } = false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value is IList)
            {
                var list = value as IList;
                if (list.Count > LimitLength)
                {
                    return new ValidationResult("集合类型超出规定长度！");
                }
                if (list.Count == 0 && !IsNullOrZero)
                {
                    return new ValidationResult("集合长度为0！");
                }
            }
            else
            {
                if (IsNullOrZero)
                    return ValidationResult.Success;
            }
            return ValidationResult.Success;

        }
    }
}
